package spring.validation;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.me.common.util.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.validation.FieldError;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * Spring Validator 测试类：
 * TODO web 应用自定义校验器 https://blog.csdn.net/fred_lzy/article/details/81099699
 *
 * @author ME
 * @date   2019/10/21
 */
public class TestValidator {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

        // 使用 javax.validation.Validator 校验1
        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        Validator validator1 = validatorFactory.getValidator();
        Person person1 = new Person("hhhhh", "150");
        person1.setTestNotBlank("");
        doValidate(validator1, person1);

        System.out.println(StringUtils.getBytesLength("hh啊") + "\n");

        // 使用 javax.validation.Validator 校验2
        ApplicationContext context = new ClassPathXmlApplicationContext("spring/validation/validator.xml");
        Validator validator2 = context.getBean("customValidator", Validator.class);
        Person person2 = new Person.PersonBuilder("name|age|testSize|testLength|time")
            .setValues("啊aa|15|000|999a|2013-10-9 13:00:09").builder();
        doValidate(validator2, person2);

        // 使用 org.springframework.validation.Validator 自定义校验规则
        System.out.println("\nSpring Validator：");
        DataBinder binder = new DataBinder(person1);
        binder.setValidator(new PersonValidator());
        binder.validate();
        BindingResult result = binder.getBindingResult();
        result.getAllErrors().forEach(error -> {
            System.out.println(((FieldError) error).getField() + ": " + error.getCode());
        });

        System.out.println();
        ObjectMapper mapper = new ObjectMapper();
        try {
            System.out.println(mapper.writeValueAsString(person2));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }

    private static void doValidate(Validator validator, Person person) {
        Set<ConstraintViolation<Person>> validate = validator.validate(person);
        // 如果校验有值
        if (!validate.isEmpty()) {
            for (ConstraintViolation<Person> violation : validate) {
                System.out.println(violation.getPropertyPath() + ": " + violation.getMessage());
            }
        }
    }
}
